/**
 * <p>Title: ObstacleSpawner.java</p>
 * <p>Description: CS 343 Final Project. This class contains the the obstacle spawner</p>
 * @author Tim Olmstead, Brady Fetting, Erik Brown, Thales Kirk
 * @email timothy.olmstead@my.uwrf.edu, brady.fetting@my.uwrf.edu, 
 * 			erik.brown@my.uwrf.edu, thales.kirk@my.uwrf.edu
 * @date November 15, 2013
 */
package Obstacles;

import GameState.Game;

public class ObstacleSpawner implements Runnable {

	private boolean suspended = false;
	private boolean endThread = false;
	private long lastSpawn;
	private long randomSpawnTime;

	private long lastcheck;
	private final long checkwait = 16;

	/**
	 * @param none
	 * @description creates the obstacle spawner
	 */
	public ObstacleSpawner() {
		lastSpawn = System.currentTimeMillis();
		randomSpawnTime = 4000;
		lastcheck = System.currentTimeMillis();
	}

	@Override
	public void run() {
		while (Game.player.isAlive()) {
			if (!suspended) {
				// timer for updating
				if (lastcheck + checkwait < System.currentTimeMillis()) {
					lastcheck = System.currentTimeMillis();
					// timer for spawing
					if (lastSpawn + randomSpawnTime < System
							.currentTimeMillis()) {
						Game.getObstacleContainer().addObstacle(
								new MoveableObstacle());
						lastSpawn = System.currentTimeMillis();

						// WILL NEED TWEEKING TO AVOID TWO OBJECTS SPAWNING
						// RIGHT NEXT TO EACH OTHER
						randomSpawnTime = 2000 + (long) (Math.random() * 2000);
					}
				}
			}
			try {
				Thread.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			if (endThread) {
				randomSpawnTime = 4000;
				break;
			}
		}
	}

	/**
	 * @param none
	 * @description suspends the current thread
	 */
	public void suspendThread() {
		suspended = true;
	}

	/**
	 * @param none
	 * @description unsuspends the current thread
	 */
	public void unsuspendThread() {
		suspended = false;
	}

	/**
	 * @param none
	 * @description ends the current thread
	 */
	public void endThread() {
		endThread = true;
		randomSpawnTime = 4000;
	}

	/**
	 * @param none
	 * @description enables the current thread
	 */
	public void enableThread() {
		endThread = false;
	}

}
